package ioperations;

import book.Book;
import book.BookList;

import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 姚东名
 * Date: 2024-06-14
 * Time: 14:33
 */
public class AddOperation implements IOperation {
    @Override
    public void work(BookList bookList) {
        System.out.println("添加图书！");

        //第一步：判断书架是否已经装满书本了
        int currentSize = bookList.getUsedSize();
        if(currentSize == bookList.getBooks().length) {
            System.out.println("书架已经放满了，不能再放了！");
            return;
        }

        //第二步：构造对象：一本书 = 书名 + 作者 + 书的类型 + 价格
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入书名：");
        String name = scanner.nextLine();

        System.out.println("请输入作者：");
        String author = scanner.nextLine();

        System.out.println("请输入书的类型：");
        String type = scanner.nextLine();

        System.out.println("请输入价格：");
        int price = scanner.nextInt();

        Book newBook = new Book(name, author, price, type);

        //第三步：判断书架上是否有这本书
        for (int i = 0; i < currentSize; i++) {
            Book book = bookList.getBook(i);
            if(book.getName().equals(name)) {
                System.out.println("这本书存在于书架上，不能插入！");
                return;
            }
        }

        //第四步：插入图书
        bookList.setBook(currentSize, newBook);
        //有效数据自增1
        bookList.setUsedSize(currentSize + 1);

        System.out.println("新增图书成功！");
    }
}
